<template>
  <div
    class="vk-collapse-item"
    :class="{
      'is-disabled': disabled,
    }"
  >
    <div
      class="vk-collapse-item__header"
      :class="{
        'is-disabled': disabled,
        'is-active': isActive,
      }"
      :id="`item-header-${name}`"
      @click="handleClick"
    >
      <slot name="title">{{ title }}</slot>
      <Icon icon="angle-right" class="header-angle" />
    </div>
    <Transition name="slide" v-on="transitionEvents">
      <div class="vk-collapse-item__wrapper" v-show="isActive">
        <div class="vk-collapse-item__content" :id="`item-content-${name}`">
          <slot />
        </div>
      </div>
    </Transition>
  </div>
</template>

<script setup lang="ts">
import { inject, computed } from "vue";
import type { CollapseItemProps } from "./types";
import { collapseContextKey } from "./types";
import Icon from "../Icon/Icon.vue";

// 设置组件名称为 'VkCollapseItem'
defineOptions({
  name: "VkCollapseItem",
});

const props = defineProps<CollapseItemProps>();
const collapseContext = inject(collapseContextKey);

// 计算属性：判断当前项是否是激活状态
const isActive = computed(() => collapseContext?.activeNames.value.includes(props.name));

// 处理头部点击事件
const handleClick = () => {
  if (props.disabled) {
    return;
  } // 如果当前项被禁用，直接返回
  collapseContext?.handleItemClick(props.name); // 调用父组件的点击处理函数
};

// 定义 Transition 组件的动画事件 Record用于定义一个对象的键值对结构
const transitionEvents: Record<string, (el: HTMLElement) => void> = {
  // 进入动画开始前
  beforeEnter(el) {
    el.style.height = "0px"; // 设置高度为 0
    el.style.overflow = "hidden"; // 隐藏溢出内容
  },
  // 进入动画进行中
  enter(el) {
    el.style.height = `${el.scrollHeight}px`; // 设置高度为内容实际高度
  },
  // 进入动画结束后
  afterEnter(el) {
    el.style.height = ""; // 恢复高度
    el.style.overflow = ""; // 恢复溢出处理
  },
  // 离开动画开始前
  beforeLeave(el) {
    el.style.height = `${el.scrollHeight}px`; // 设置高度为内容实际高度
    el.style.overflow = "hidden"; // 隐藏溢出内容
  },
  // 离开动画进行中
  leave(el) {
    el.style.height = "0px"; // 设置高度为 0
  },
  // 离开动画结束后
  afterLeave(el) {
    el.style.height = ""; // 恢复高度
    el.style.overflow = ""; // 恢复溢出处理
  },
};
</script>
